package com.gxa.ssm340.service.impl;

import com.gxa.ssm340.common.ErrorCode;
import com.gxa.ssm340.entity.dto.ExchangeGoodsDTO;
import com.gxa.ssm340.entity.dto.SubmitPointsDTO;
import com.gxa.ssm340.entity.dto.UserPointsDTO;
import com.gxa.ssm340.entity.pojo.Goods;
import com.gxa.ssm340.entity.pojo.Points;
import com.gxa.ssm340.entity.pojo.User;
import com.gxa.ssm340.exception.BizException;
import com.gxa.ssm340.mapper.PointsCancelMapper;
import com.gxa.ssm340.service.PointsCancelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class PointsCancelServiceImpl implements PointsCancelService {
    @Autowired
    private PointsCancelMapper mapper;


    @Override
    public UserPointsDTO getTotalPointsByPhone(String phone) throws BizException {
//        if (StringUtils.isEmpty(phone) || "".equals(phone)){
//            throw new BizException(ErrorCode.NULL_FIELD);
//        }
//        if (!phone.matches("(\\d{11})|^((\\d{7,8})|(\\d{4}|\\d{3})-(\\d{7,8})-(\\d{4}|\\d{3}|\\d{2}|\\d{1})|(\\d{7,8})-(\\d{4}|\\d{3}|\\d{2}|\\d{1}))$")){
//            throw new BizException(ErrorCode.WRONG_PHONE);
//        }
        UserPointsDTO dto = mapper.selectTotalPointsByPhone(phone);
        if (dto.getUserId()==null){
            throw new BizException(ErrorCode.NULL_USER);
        }
        return dto;
    }


    @Override
    public List<Goods> getAllGoods() {
        return mapper.selectAllGood();
    }



    @Override
    public Integer addExchangeGoods(ExchangeGoodsDTO dto) {
        User user = mapper.selectByPhone(dto.getPhone());
        Goods goods = mapper.selectGoodsById(dto.getGoodsId());
        Points points = new Points();
        points.setPoints(Math.negateExact(goods.getIntegral()));
        points.setImg(goods.getImage());
        points.setPhone(user.getPhone());
        points.setBrandName(goods.getName());
        points.setNum(1);
        points.setPhone(dto.getPhone());
        points.setUserId(user.getUserId());
        Integer first = mapper.insertExchangeGood(dto);
        Integer second= mapper.insertPoints(points);
        goods.setNumber(goods.getNumber()-1);
        mapper.updateGoodsNum(goods);
        if (first >0 && second>0){
            return 1;
        }
        return 0;
    }

    @Override
    public Integer addPoints(SubmitPointsDTO dto) {
        dto.setUserId(mapper.selectByPhone(dto.getPhone()).getUserId());
        return mapper.insertSubmitPoints(dto);
    }
}
